package main

import (
	"awesomeProject/goAgentServer/db"
	sshserver "awesomeProject/goAgentServer/server"
	"awesomeProject/goAgentServer/web"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"syscall"
)

type conf struct {
	SshBindAddr  string `json:"sshBindAddr"`
	WebBindAaddr string `json:"webBindAaddr"`
	WebUsername  string `json:"webUsername"`
	WebPasswd    string `json:"webPasswd"`
	Mysql        string `json:"mysql"`
	SftpDir      string `json:"sftpDir"`
	SessionDir   string `json:"sessionDir"`
}

var c conf

const version = "v0.0.2 2023-7-22"

func init() {
	log.SetPrefix("main: ")
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	confByte, err := ioutil.ReadFile("./conf.json")
	if err != nil {
		log.Panicln("open conf.json errors ", err)
	}

	err = json.Unmarshal(confByte, &c)
	if err != nil {
		log.Panicln("read conf.json errors ", err)
	}
	log.Println("read conf.json values: ", c, "version:", version)
}

func main() {

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan)

	go func() {
		for {
			s := <-sigChan
			switch s {
			case syscall.SIGTERM, syscall.SIGINT:
				log.Println("system exited")
				os.Exit(0)
			case syscall.SIGKILL:
				log.Println("The system is forced to stop")
				os.Exit(1)
			}
		}
	}()

	var w web.WebInfo
	w.Username = c.WebUsername
	w.Password = c.WebPasswd
	w.Addr = c.WebBindAaddr

	db.InitDB(c.Mysql)
	sshserver.SftpDir = c.SftpDir
	sshserver.SessionDir = c.SessionDir

	go w.RunHttpServers()
	sshserver.StartSshServer(c.SshBindAddr)
	log.Println("start servers successful..")
}
